﻿#include "ObjectPool.h"
#include "ConcurrentAlloc.h"

void Alloc1()
{
	for (int i = 0; i < 5; i++)
	{
		void* ptr = ConcurrentAlloc(5);
	}
}

void Alloc2()
{
	for (int i = 0; i < 5; i++)
	{
		void* ptr = ConcurrentAlloc(5);
	}
}

void TestThreadCache()
{
	std::thread t1(Alloc1);
	std::thread t2(Alloc2);

	t1.join();
	t2.join();
}

void tcmalloc1()
{
	void* p1 = ConcurrentAlloc(6);
	void* p2 = ConcurrentAlloc(6);
	void* p3 = ConcurrentAlloc(6);
	void* p4 = ConcurrentAlloc(6);
	void* p5 = ConcurrentAlloc(6);
}

#include <atomic>
std::atomic<int> cnt = 0;
void tcmalloc2()
{
	for (int i = 0; i < 1024; i++)
	{
		int n = rand()%10+1;
		// int n = 100*1024;
		// cout << n << endl;
		void* p1 = ConcurrentAlloc(n);
		cnt++;
		// cout << cnt*100 << endl;

		//cout << p1 << endl;
	}
	void* p2 = ConcurrentAlloc(8);
	//cout << p2 << endl;
}

void TestThreadCache2()
{
	std::thread t1(tcmalloc2);
	//t1.join();
	std::thread t2(tcmalloc2);

	t1.join();
	t2.join();
}

void Test1()
{
	std::vector<std::pair<void*, size_t>> v;
	for (int i = 0; i < 1024; i++)
	{
		int n = rand()%100+1;
		v.emplace_back(ConcurrentAlloc(n), n);
		//v[i].first = &n;
	}
	for(auto e : v)
	{
		// cout << e.second << endl;
		ConcurrentFree(e.first, e.second);
	}
}

void HardTest()
{
	std::thread t1(Test1);
	//t1.join();
	std::thread t2(Test1);
	std::thread t3(Test1);
	std::thread t4(Test1);
	std::thread t5(Test1);
	std::thread t6(Test1);
	std::thread t7(Test1);
	std::thread t8(Test1);
	std::thread t9(Test1);
	std::thread t10(Test1);
	std::thread t11(Test1);
	std::thread t12(Test1);

	t1.join();
	t2.join();
	t3.join();
	t4.join();
	t5.join();
	t6.join();
	t7.join();
	t8.join();
	t9.join();
	t10.join();
	t11.join();
	t12.join();
}

void Test2()
{
	std::vector<std::pair<void*, size_t>> v;
	for (int i = 0; i < 1; i++)
	{
		int n = 8;
		v.emplace_back(ConcurrentAlloc(n), n);
	}
	for (auto e : v)
	{
		ConcurrentFree(e.first, e.second);
	}
}

void EasyTest()
{
	std::thread t1(Test2);
	std::thread t2(Test2);

	t1.join();
	t2.join();

}


int main()
{
	srand(time(nullptr));
	// TestObjectPool();
	// TestThreadCache();

	// tcmalloc2();
	// TestThreadCache2();
	
	//EasyTest();
	HardTest();
	return 0;
}